# 电磁学科后处理
from multiprocessing import Process, Queue
import time
import vtkmodules.all as vtk


# 每一行数据 x,y,z 带一个标量数据
class ElectromagnetismDataReader:
    max_cpu = 4

    def __init__(self):
        self.points = vtk.vtkPoints()
        self.poly_data = vtk.vtkPolyData()
        self.cells = vtk.vtkCellArray()
        self.scalars = vtk.vtkFloatArray()
        self.origin = []

    def read(self, path: str):
        start_time = time.time()
        with open(path, 'r', encoding='utf-8') as f:
            for line in f:
                # 处理每一行
                content = line.strip().split()
                self.origin.extend(content)
        f.close()
        print("解析时间", time.time() - start_time)
        self.create_points(self.origin)
        self.create_poly_data()
        self.insert_scalars(self.origin)

    def read_from_remote(self, url: str):
        return

    def create_points(self, data):
        i = 0
        while i < len(data) / 4:
            # 添加点的数据
            self.points.InsertNextPoint(
                [float(data[i]), float(data[i + 1]), float(data[i + 2])])
            i += 4

    def create_poly_data(self):
        self.poly_data.SetPoints(self.points)

    def insert_scalars(self, data):
        i = 0
        while i < len(data) / 4:
            self.scalars.InsertNextValue(float(data[i + 3]))
            i += 4
            # 将标量数据添加到点云数据中
        self.poly_data.GetPointData().SetScalars(self.scalars)

    def get_scalar_range(self):
        return self.scalars.GetRange()

    def get_poly_data(self):
        return self.poly_data
